#!/bin/sh

set -e

t=`mktemp -d -t adb-channel.XXXXXX`

remote=${1}
activity=${2}
delay=${3}

atexit() {
  [ -z "${activity}" ] || adb shell am force-stop ${activity%%/*}
  adb forward --remove localfilesystem:"${t}/sock"
  rm -rf "${t}"
}
trap atexit EXIT
trap 'exit 0' HUP INT ALRM TERM

[ -z "${activity}" ] || adb shell -n am start -W ${activity}
[ -z "${delay}" ] || sleep "${delay}"
adb forward localfilesystem:"${t}/sock" "${remote}"
socat stdio unix:"${t}/sock"
